<template>
  <div class="assignPermission">
    <!-- show-checkbox : 显示复选框 -->
    <el-tree ref="tree" v-loading="loading" node-key="id" check-strictly default-expand-all show-checkbox :data="permissionData" :props="{label:'name'}" :expand-on-click-node="false" />

    <el-row type="flex" justify="end">
      <el-col :span="6">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPerm, getRoleDetail } from '@/api/roles'
export default {
  name: 'AssignPermission',
  components: {},
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: [], // 存储权限数据
      loading: false
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleDetail()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      this.loading = true
      try {
        const res = await getPermissionList()
        this.permissionData = tranListToTreeData(res.data)
        this.loading = false
      } catch (e) {
        console.log(e)
      }
    },
    // 确定按钮,分配权限
    async hSubmit() {
      try {
        const ids = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.id, permIds: ids })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 获取用户角色有哪些权限
    async getRoleDetail() {
      try {
        const res = await getRoleDetail(this.id)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
